package com.futvan.z.system.zjob;
import java.util.HashMap;

import org.springframework.stereotype.Service;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.SuperService;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.JobUtil;
@Service
public class ZjobService extends SuperService{

	public Result start_job(HashMap<String, String> bean){
		Result result = new Result();
		String JobId = bean.get("zid");
		z_job job = selectBean("select * from z_job where zid = '"+JobId+"'",z_job.class);
		String JobClass = job.getJobclass();
		String CronExpression = job.getJobtime();
		//判断参数是否为空
		if(z.isNotNull(JobId) && z.isNotNull(JobClass) && z.isNotNull(CronExpression)) {
			try {
				//添加任务，如果出异常返回错误
				JobUtil.jobAdd(JobId, JobClass, CronExpression);
				result.setCode(Code.SUCCESS);
				//变更任务状态
				int num = update("update z_job set isstart = '1' where zid = '"+JobId+"'");
				if(num!=1) {
					//删除已启动的任务
					JobUtil.jobDelete(JobId);
					z.Exception("变更任务状态出错");
				}
			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg(e.getMessage());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("/start_job error JobId or JobClass or CronExpression is null");
		}
		return result;
	}

	

	public Result close_job(HashMap<String, String> bean) {
		Result result = new Result();
		String JobId = bean.get("zid");
		//判断参数是否为空
		if(z.isNotNull(JobId)) {
			try {
				//变更任务状态
				int num = update("update z_job set isstart = '0' where zid = '"+JobId+"'");
				if(num==1) {
					//删除任务，如果出异常返回错误
					JobUtil.jobDelete(JobId);
					result.setCode(Code.SUCCESS);
				}else {
					z.Exception("变更任务状态出错");
				}
			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg(e.getMessage());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("/start_job error JobId  is null");
		}
		return result;
	}

	public Result run_job(HashMap<String, String> bean) {
		Result result = new Result();
		String JobId = bean.get("zid");
		z_job job = selectBean("select * from z_job where zid = '"+JobId+"'",z_job.class);
		String JobClass = job.getJobclass();
		//判断参数是否为空
		if(z.isNotNull(JobId) && z.isNotNull(JobClass)) {
			try {
				//执行任务，如果出异常返回错误
				JobUtil.jobRun(JobId, JobClass);
				result.setCode(Code.SUCCESS);
			} catch (Exception e) {
				result.setCode(Code.ERROR);
				result.setMsg(e.getMessage());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("/start_job error JobId or JobClass is null");
		}
		return result;
	}
}
